#!/bin/sh
# shellcheck disable=SC3043

success() {
  local MSG="$1"
  printf "✔ SUCCESS: %s\n" "$MSG"
}

fail() {
  local MSG="$1"
  printf "✗ FAIL: %s\n" "$MSG"
  return 1
}

fail_no_return() {
  local MSG="$1"
  printf "✗ FAIL: %s\n" "$MSG"
}

assert_string_contains() {
  EXPECTED="$1"
  ACTUAL="$2"

  if echo "$ACTUAL" | grep -F "$EXPECTED" > /dev/null
  then 
    success "$ACTUAL contains $EXPECTED"
  else
    fail "$ACTUAL doesn't contain $EXPECTED"
  fi
}

assert_string_equal(){
  EXPECTED="$1"
  ACTUAL="$2"

  if [ "$ACTUAL" = "$EXPECTED" ]
  then 
    success "$ACTUAL is equal to $EXPECTED"
  else
    fail "$ACTUAL is not equal to $EXPECTED"
  fi
}

assert_string_not_equal(){
  EXPECTED="$1"
  ACTUAL="$2"

  if [ "$ACTUAL" = "$EXPECTED" ]
  then 
    fail "$ACTUAL is equal to $EXPECTED"
  else
    success "$ACTUAL is not equal to $EXPECTED"
  fi
}

assert_greater_than(){
  local EXPECTED="$1"
  local ACTUAL="$2"

  if [ "$ACTUAL" -gt "$EXPECTED" ]
  then 
    success "$ACTUAL is greater than $EXPECTED"
  else
    fail "$ACTUAL is not is greater than $EXPECTED"
  fi
}

assert_api_error(){
  RESPONSE="$1"
  EXPECTED_ERROR_TYPE="${EXPECTED_ERROR_TYPE:-"constraint-violation"}"
  EXPECTED_ERROR_TITLE="${EXPECTED_ERROR_TITLE:-"do not comply with the syntactic rules"}"
  EXPECTED_ERROR_DETAIL="${EXPECTED_ERROR_DETAIL:-"in body"}"
  EXPECTED_ERROR_FIELD="${EXPECTED_ERROR_FIELD:-""}"
  ERROR_TYPE="$(echo true | jq --arg response "$RESPONSE" '$response | fromjson | .type' )"

  assert_string_contains "$EXPECTED_ERROR_TYPE" "$ERROR_TYPE"

  ERROR_TITLE="$(echo true | jq --arg response "$RESPONSE" '$response | fromjson | .title' )"

  assert_string_contains "$EXPECTED_ERROR_TITLE" "$ERROR_TITLE"

  ERROR_DETAIL="$(echo true | jq --arg response "$RESPONSE" '$response | fromjson | .detail' )"

  assert_string_contains "$EXPECTED_ERROR_DETAIL" "$ERROR_DETAIL"

  if [ "$EXPECTED_ERROR_FIELD" != "" ]
  then
    ERROR_FIELD="$(echo true | jq --arg response "$RESPONSE" '$response | fromjson | .fields[0]' )"
    assert_string_contains "$EXPECTED_ERROR_FIELD" "$ERROR_FIELD"
  fi
}
